﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MicroLED_Detecter
{
    public partial class FormScanResult : Form
    {
        int view_flag = 1;
        public FormScanResult()
        {
            InitializeComponent();
        }

        private void FormScanResult_FormClosing(object sender, FormClosingEventArgs e)
        {
            ((FormMain)Owner).Toggletsb_Img(true);//只能打开一个FormScanResult
        }

        string folderPath = @"data\scanImg";// 储存扫描照片的5个文件夹的保存路径
        string scanRecordRenewTime_txtPath = @"data\scanRecordRenewTime.txt";// 定义储存扫描记录更新时间的txt文件路径
        string scanRecordRenewTime;// 扫描记录更新时间

        private void UpdateScanRecords()// 更新扫描记录  
        {                    
            string[] subDirectories = Directory.GetDirectories(folderPath);// 获取目标路径下的所有文件夹（5个）
            // 按照创建时间降序排序
            Array.Sort(subDirectories, (x, y) => String.Compare(y, x));
            // 存储每个txt文件中的文本
            string[] texts = new string[5];
            // 依次读取每个文件夹中的txt文件
            for (int i = 0; i < subDirectories.Length; i++)
            {
                string txt_folderPath = subDirectories[i];
                string[] txtFiles = Directory.GetFiles(txt_folderPath, "data.txt");
                // 读取第一个txt文件的内容
                string fileContent = File.ReadAllText(txtFiles[0]);
                // 将文件内容存储到对应的数组元素中
                texts[i] = fileContent;

            }
            // 保存到对应的字符串变量中
            string scanRecord1 = texts[0];
            string scanRecord2 = texts[1];
            string scanRecord3 = texts[2];
            string scanRecord4 = texts[3];
            string scanRecord5 = texts[4];

            string[] scanRecords = { scanRecord1, scanRecord2, scanRecord3, scanRecord4, scanRecord5 };
            for (int i = 0; i < scanRecords.Length; i++)
            {
                //将文本分割
                string scanRecord = scanRecords[i];
                string[] parts_scanRecord = scanRecord.Split(' ');

                string scanRecord_Timeyyyy = parts_scanRecord[0];
                string scanRecord_TimeMM = parts_scanRecord[1];
                string scanRecord_Timedd = parts_scanRecord[2];
                string scanRecord_TimeHH = parts_scanRecord[3];
                string scanRecord_Timemm = parts_scanRecord[4];
                string scanRecord_Timess = parts_scanRecord[5];
                string scanRecord_rowcount = parts_scanRecord[6];
                string scanRecord_columncount = parts_scanRecord[7];

                string label_scanRecordTime = "label_scanRecordTime" + (i + 1);
                string label_scanRecordCount = "label_scanRecordCount" + (i + 1);

                // 查找扫描纪录标签控件,更新扫描纪录
                Label lbl_scanRecordTime = this.Controls.Find(label_scanRecordTime, true).FirstOrDefault() as Label;
                Label lbl_scanRecordCount = this.Controls.Find(label_scanRecordCount, true).FirstOrDefault() as Label;
                lbl_scanRecordTime.Text = scanRecord_Timeyyyy + "." + scanRecord_TimeMM + "." + scanRecord_Timedd + "_" + scanRecord_TimeHH + ":" + scanRecord_Timemm + ":" + scanRecord_Timess;
                lbl_scanRecordCount.Text = scanRecord_rowcount + "×" + scanRecord_columncount;
            }
        }

        private void ReadFile_UpdatedTime()// 读取扫描记录更新时间的txt文件，并更新更新时间控件
        {
            // 读取扫描记录更新时间的txt文件
            scanRecordRenewTime = File.ReadAllText(scanRecordRenewTime_txtPath);
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] parts = scanRecordRenewTime.Split(' ');
            string scanRecordRenewTime_1 = parts[0];
            string scanRecordRenewTime_2 = parts[1];
            string scanRecordRenewTime_3 = parts[2];
            string scanRecordRenewTime_4 = parts[3];
            string scanRecordRenewTime_5 = parts[4];
            string scanRecordRenewTime_6 = parts[5];
            // 更新更新时间
            label_scanRecordRenewTime.Text = "上次更新时间：" + scanRecordRenewTime_1 + "." + scanRecordRenewTime_2 + "." + scanRecordRenewTime_3 + "_" + scanRecordRenewTime_4 + ":" + scanRecordRenewTime_5 + ":" + scanRecordRenewTime_6;
        }

        private void FormScanResult_Load(object sender, EventArgs e)
        {
            UpdateScanRecords();
            ReadFile_UpdatedTime();

            // 设置 DataGridView 的列数
            dataGridView_scanResult.ColumnCount = 10;
            // 设置 DataGridView 的行数
            dataGridView_scanResult.RowCount = 10;
            for (int i = 0; i < 10; i++)
                dataGridView_scanResult.Columns[i].HeaderText = $"Col{i + 1}";
            for (int i = 0; i < 10; i++)
                dataGridView_scanResult.Rows[i].HeaderCell.Value = $"Row{i + 1}";

            // 如果PictureBox已经有图像，先释放内存
            if (pb_scanResult.Image != null)
            {
                pb_scanResult.Image.Dispose();
                pb_scanResult.Image = null;
            }
            string detection_pohoto_path = @"data\logo\detection.png";
            // 加载照片到PictureBox控件
            Image photo = Image.FromFile(detection_pohoto_path);
            pb_scanResult.Image = photo;

            tbx_FlagQ.Enabled = false;
            tbx_FlagD.Enabled = false;
            gb_detectionInformation.Enabled = false;
        }

        private void btn_scanRecordRenew_Click(object sender, EventArgs e)
        {
            UpdateScanRecords();

            // 更新扫描记录更新时间的txt文件
            scanRecordRenewTime = DateTime.Now.ToString("yyyy MM dd HH mm ss");
            File.WriteAllText(scanRecordRenewTime_txtPath, scanRecordRenewTime);

            ReadFile_UpdatedTime();
        }
        private void linkLabel_scanRecordResult1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            scanResultShow(1);
            view_flag = 1;
        }

        private void linkLabel_scanRecordResult2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            scanResultShow(2);
            view_flag = 2;
        }

        private void linkLabel_scanRecordResult3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            scanResultShow(3);
            view_flag = 3;
        }

        private void linkLabel_scanRecordResult4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            scanResultShow(4);
            view_flag = 4;
        }

        private void linkLabel_scanRecordResult5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            scanResultShow(5);
            view_flag = 5;
        }
        private void scanResultShow(int num)
        {
            gb_detectionInformation.Enabled = true;
            gb_detectionInformation.Text = "扫描" + num + "-检测结果查看";
            string arry_text = Controls.Find("label_scanRecordCount" + num, true)[0].Text;
            // 去除空格并按乘号分割字符串
            string[] arry_parts = arry_text.Split('×');
            int row = int.Parse(arry_parts[0]);
            int col = int.Parse(arry_parts[1]);


            //// 考虑到如果列数过大，则要一列一列创建并设置其宽度，因为列的 FillWeight 值总和不能超过 65535
            //for (int i = 0; i < col; i++)
            //{
            //    // 创建新列并设置属性
            //    DataGridViewColumn column = new DataGridViewTextBoxColumn();
            //    column.HeaderText = $"Col{i + 1}";
            //    column.FillWeight = 10;

            //    // 将新列添加到控件中
            //    dataGridView_scanResult.Columns.Add(column);
            //}

            // 设置 DataGridView 的列数
            dataGridView_scanResult.ColumnCount = col;
            for (int i = 0; i < col; i++)
                dataGridView_scanResult.Columns[i].HeaderText = $"Col{i + 1}";

            // 设置 DataGridView 的行数
            dataGridView_scanResult.RowCount = row;
            for (int i = 0; i < row; i++)
                dataGridView_scanResult.Rows[i].HeaderCell.Value = $"Row{i + 1}";

            string filename_text = Controls.Find("label_scanRecordTime" + num, true)[0].Text;
            string[] filename_parts = filename_text.Split(new char[] { '.', '_', ':' });
            string filename = string.Join(" ", filename_parts);
            string searchpath = @"data\scanImg\" + filename;
            string[] photoFiles = Directory.GetFiles(searchpath, "*.jpg");
            int chip_count = 0;
            int Qchip_count = 0;
            int Dchip_count = 0;
            int Unknownchip_count = 0;
            // 循环遍历每个单元格，设置其值
            for (int i = 0; i < dataGridView_scanResult.RowCount; i++)
            {
                for (int j = 0; j < dataGridView_scanResult.ColumnCount; j++)
                {
                    dataGridView_scanResult[j, i].Style.BackColor = Color.White;
                    for (int k = 0; k < photoFiles.Length; k++)//考虑到扫描中断，照片不全的情况，单元格只显示已拍摄照片的信息
                    {
                        string photoName = Path.GetFileName(photoFiles[k]);// 照片名，例Image_2_3.jpg
                        string[] photoName_parts = photoName.Split(new char[] { '_', '.' });
                        int row_now = int.Parse(photoName_parts[1]);
                        int col_now = int.Parse(photoName_parts[2]);
                        if (row_now == i + 1 && col_now == j + 1)
                        {
                            dataGridView_scanResult[j, i].Value = $"{i + 1}×{j + 1}";// 在第一行第一列上写入 "1×1"，第一行第二列上写入 "1×2"，以此类推，前提是该行该列对应的照片有拍摄
                            string txt_filepath = Path.Combine(searchpath, $"Image_{i + 1}_{j + 1}.txt");
                            string txt_content = File.ReadAllText(txt_filepath);// 读取文本文件的内容,例如1 Q
                            string[] txt_content_parts = txt_content.Split(new char[] { ' ' });
                            int chipNumber = int.Parse(txt_content_parts[0]);                          
                            if (chipNumber == 1)
                            {
                                string chipStatus = txt_content_parts[1];
                                if (chipStatus == "D")
                                {
                                    dataGridView_scanResult[j, i].Style.BackColor = Color.Red;
                                    Dchip_count++;
                                }
                                else if (chipStatus == "Q")
                                {
                                    dataGridView_scanResult[j, i].Style.BackColor = Color.Green;
                                    Qchip_count++;
                                }
                            }
                            else
                            {
                                dataGridView_scanResult[j, i].Style.BackColor = Color.Gray;
                                Unknownchip_count++;
                            }
                            break;
                        }
                    }
                }
            }
            chip_count = Qchip_count + Dchip_count + Unknownchip_count;
            label_detectionInformation.Text = "扫描" + view_flag + "-检测结果\n\n\n检测到" + chip_count + "个芯片\n\n  合格芯片数：" + Qchip_count + "\n\n  缺陷芯片数：" + Dchip_count + "\n\n    缺陷一(芯片缺位)数：" + Dchip_count + "\n\n  未知芯片数：" + Unknownchip_count;
            // 添加 DataGridView 单元格点击事件的处理方法
            dataGridView_scanResult.CellClick += DataGridView_scanResult_CellClick;

            // 加载第1×1张图片
            if (chip_count != 0)// 至少有一张照片
            {
                // 如果PictureBox已经有图像，先释放内存
                if (pb_scanResult.Image != null)
                {
                    pb_scanResult.Image.Dispose();
                    pb_scanResult.Image = null;
                }
                string pohoto_path = Path.Combine(searchpath, "Image_1_1.jpg");
                // 加载照片到PictureBox控件
                Image photo = Image.FromFile(pohoto_path);
                pb_scanResult.Image = photo;

                label_SingleChipView.Text = "正在显示第1×1个芯片，检测结果:";
                string SingleChipResult_path = Path.Combine(searchpath, "Image_1_1.txt");
                string txt_content = File.ReadAllText(SingleChipResult_path);// 读取文本文件的内容,例如1 Q
                string[] txt_content_parts = txt_content.Split(new char[] { ' ' });
                int chipNumber = int.Parse(txt_content_parts[0]);              
                if (chipNumber == 1) 
                {
                    string chipStatus = txt_content_parts[1];
                    if (chipStatus == "D")
                        label_SingleChipResult.Text = "缺陷一(芯片缺位)";
                    else if (chipStatus == "Q")
                        label_SingleChipResult.Text = "合格";
                }
                else
                {
                    label_SingleChipResult.Text = "未知";
                }
            }
        }
        private void ShowOneChipResult(int row, int column)
        {
            string filename_text = Controls.Find("label_scanRecordTime" + view_flag, true)[0].Text;
            string[] filename_parts = filename_text.Split(new char[] { '.', '_', ':' });
            string filename = string.Join(" ", filename_parts);
            string searchpath = @"data\scanImg\" + filename;
            string[] photoFiles = Directory.GetFiles(searchpath, "*.jpg");
            for (int k = 0; k < photoFiles.Length; k++)
            {
                string photoName = Path.GetFileName(photoFiles[k]);// 照片名，例Image_2_3.jpg
                string[] photoName_parts = photoName.Split(new char[] { '_', '.' });
                int row_now = int.Parse(photoName_parts[1]);
                int col_now = int.Parse(photoName_parts[2]);
                if (row_now == row && col_now == column)
                {
                    // 如果PictureBox已经有图像，先释放内存
                    if (pb_scanResult.Image != null)
                    {
                        pb_scanResult.Image.Dispose();
                        pb_scanResult.Image = null;
                    }
                    string pohoto_path = Path.Combine(searchpath, photoName);
                    // 加载照片到PictureBox控件
                    Image photo = Image.FromFile(pohoto_path);
                    pb_scanResult.Image = photo;

                    label_SingleChipView.Text = "正在显示第" + row + "×" + column + "个芯片，检测结果:";
                    string SingleChipResult_path = Path.Combine(searchpath, "Image_" + row + "_" + column + ".txt");
                    // string SingleChipResult_path = Path.Combine(searchpath, $"Image_{row}_{column}.txt");
                    string txt_content = File.ReadAllText(SingleChipResult_path);// 读取文本文件的内容,例如1 Q
                    string[] txt_content_parts = txt_content.Split(new char[] { ' ' });
                    int chipNumber = int.Parse(txt_content_parts[0]);                  
                    if (chipNumber == 1)
                    {
                        string chipStatus = txt_content_parts[1];
                        if (chipStatus == "D")
                            label_SingleChipResult.Text = "缺陷一(芯片缺位)";
                        else if (chipStatus == "Q")
                            label_SingleChipResult.Text = "合格";
                    }
                    else
                    {
                        label_SingleChipResult.Text = "未知";
                    }
                    break;
                }
            }
        }

        private void DataGridView_scanResult_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 获取点击的单元格的行号和列号
            ShowOneChipResult(e.RowIndex + 1, e.ColumnIndex + 1);
        }

        private void btn_SingleView_Click(object sender, EventArgs e)
        {
            // 获取要查看的行列号
            ShowOneChipResult(int.Parse(tbx_SingleViewRow.Text), int.Parse(tbx_SingleViewCol.Text));
        }
    }
}
